<template>
    <div class="user-management">
        <div class="page-header">
            <h1>
                <i class="icon">👥</i>
                用户管理
            </h1>
            <button @click="showAddUserDialog" class="btn btn-primary">
                <i class="icon">➕</i>
                添加用户
            </button>
        </div>

        <!-- 搜索和筛选 -->
        <div class="filter-bar">
            <div class="search-box">
                <i class="icon">🔍</i>
                <input 
                    v-model="searchKeyword" 
                    @input="handleSearch"
                    type="text" 
                    placeholder="搜索用户名、邮箱..."
                />
            </div>
            <select v-model="filterRole" @change="fetchUsers" class="role-filter">
                <option value="">全部角色</option>
                <option value="admin">管理员</option>
                <option value="editor">编辑</option>
                <option value="user">普通用户</option>
            </select>
        </div>

        <!-- 用户列表 -->
        <div class="user-list">
            <div v-if="loading" class="loading">
                <i class="icon">⏳</i>
                加载中...
            </div>
            
            <table v-else-if="users.length > 0">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>角色</th>
                        <th>状态</th>
                        <th>注册时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="user in users" :key="user.id">
                        <td>{{ user.id }}</td>
                        <td>
                            <div class="user-info">
                                <div class="avatar">👤</div>
                                <span>{{ user.username }}</span>
                            </div>
                        </td>
                        <td>{{ user.email }}</td>
                        <td>
                            <span :class="['role-badge', `role-${user.role}`]">
                                {{ getRoleLabel(user.role) }}
                            </span>
                        </td>
                        <td>
                            <span :class="['status-badge', user.status === 1 ? 'active' : 'inactive']">
                                {{ user.status === 1 ? '正常' : '禁用' }}
                            </span>
                        </td>
                        <td>{{ formatDate(user.createdAt) }}</td>
                        <td class="actions">
                            <button @click="editUser(user)" class="btn-icon" title="编辑">
                                <i class="icon">✏️</i>
                            </button>
                            <button @click="toggleStatus(user)" class="btn-icon" title="切换状态">
                                <i class="icon">{{ user.status === 1 ? '🚫' : '✅' }}</i>
                            </button>
                            <button @click="handleDeleteUser(user)" class="btn-icon btn-danger" title="删除">
                                <i class="icon">🗑️</i>
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>
            
            <div v-else class="empty-state">
                <i class="empty-icon">👤</i>
                <p>暂无用户数据</p>
            </div>
        </div>

        <!-- 分页 -->
        <Pagination 
            v-if="total > pageSize"
            :current="currentPage"
            :total="total"
            :pageSize="pageSize"
            @change="handlePageChange"
        />

        <!-- 添加/编辑用户对话框 -->
        <div v-if="showDialog" class="dialog-overlay" @click.self="closeDialog">
            <div class="dialog">
                <div class="dialog-header">
                    <h2>{{ isEditing ? '编辑用户' : '添加用户' }}</h2>
                    <button @click="closeDialog" class="close-btn">
                        <i class="icon">✖️</i>
                    </button>
                </div>
                <div class="dialog-body">
                    <div class="form-group">
                        <label>用户名 *</label>
                        <input v-model="formData.username" type="text" placeholder="请输入用户名" />
                    </div>
                    <div class="form-group">
                        <label>邮箱 *</label>
                        <input v-model="formData.email" type="email" placeholder="请输入邮箱" />
                    </div>
                    <div class="form-group" v-if="!isEditing">
                        <label>密码 *</label>
                        <input v-model="formData.password" type="password" placeholder="请输入密码" />
                    </div>
                    <div class="form-group">
                        <label>角色 *</label>
                        <select v-model="formData.role">
                            <option value="user">普通用户</option>
                            <option value="editor">编辑</option>
                            <option value="admin">管理员</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>状态</label>
                        <select v-model.number="formData.status">
                            <option :value="1">正常</option>
                            <option :value="0">禁用</option>
                        </select>
                    </div>
                </div>
                <div class="dialog-footer">
                    <button @click="closeDialog" class="btn btn-default">取消</button>
                    <button @click="saveUser" class="btn btn-primary" :disabled="saving">
                        {{ saving ? '保存中...' : (isEditing ? '保存' : '添加') }}
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { toast } from '../utils/toast'
import { getUserList, createUser, updateUser, deleteUser, toggleUserStatus } from '../api/user'
import Pagination from '../components/Pagination.vue'

export default {
    name: 'UserManagement',
    components: {
        Pagination
    },
    setup() {
        const users = ref([])
        const total = ref(0)
        const currentPage = ref(1)
        const pageSize = ref(10)
        const searchKeyword = ref('')
        const filterRole = ref('')
        const showDialog = ref(false)
        const isEditing = ref(false)
        const loading = ref(false)
        const saving = ref(false)
        
        const formData = reactive({
            id: null,
            username: '',
            email: '',
            password: '',
            role: 'user',
            status: 1
        })

        // 获取用户列表（调用真实API）
        const fetchUsers = async () => {
            loading.value = true
            try {
                const params = {
                    current: currentPage.value,
                    size: pageSize.value
                }
                
                // 如果有搜索关键词，添加username参数
                if (searchKeyword.value.trim()) {
                    params.username = searchKeyword.value.trim()
                }
                
                const response = await getUserList(params)
                
                if (response.code === 200 && response.data) {
                    // 处理返回的数据
                    users.value = response.data.records || response.data.list || []
                    total.value = response.data.total || 0
                } else {
                    toast.error(response.message || '获取用户列表失败')
                }
            } catch (error) {
                console.error('获取用户列表失败:', error)
                toast.error(error.message || '获取用户列表失败')
            } finally {
                loading.value = false
            }
        }

        // 搜索处理（防抖）
        let searchTimer = null
        const handleSearch = () => {
            if (searchTimer) clearTimeout(searchTimer)
            searchTimer = setTimeout(() => {
                currentPage.value = 1
                fetchUsers()
            }, 500)
        }

        // 分页变化
        const handlePageChange = (page) => {
            currentPage.value = page
            fetchUsers()
        }

        // 显示添加用户对话框
        const showAddUserDialog = () => {
            isEditing.value = false
            resetForm()
            showDialog.value = true
        }

        // 编辑用户
        const editUser = (user) => {
            isEditing.value = true
            formData.id = user.id
            formData.username = user.username
            formData.email = user.email
            formData.role = user.role
            formData.status = user.status
            formData.password = ''
            showDialog.value = true
        }

        // 保存用户（调用真实API）
        const saveUser = async () => {
            // 表单验证
            if (!formData.username || !formData.email) {
                toast.error('请填写必填项')
                return
            }
            if (!isEditing.value && !formData.password) {
                toast.error('请输入密码')
                return
            }

            saving.value = true
            try {
                const userData = {
                    username: formData.username,
                    email: formData.email,
                    role: formData.role,
                    status: formData.status
                }
                
                if (!isEditing.value) {
                    userData.password = formData.password
                }

                let response
                if (isEditing.value) {
                    // 更新用户 - 在请求体中包含id
                    userData.id = formData.id
                    response = await updateUser(formData.id, userData)
                } else {
                    // 创建新用户
                    response = await createUser(userData)
                }

                if (response.code === 200) {
                    toast.success(isEditing.value ? '用户更新成功' : '用户创建成功')
                    closeDialog()
                    fetchUsers()
                } else {
                    toast.error(response.message || '操作失败')
                }
            } catch (error) {
                console.error('保存用户失败:', error)
                toast.error(error.message || '保存用户失败')
            } finally {
                saving.value = false
            }
        }

        // 删除用户（调用真实API）
        const handleDeleteUser = async (user) => {
            if (!confirm(`确定要删除用户 "${user.username}" 吗？此操作不可恢复。`)) {
                return
            }

            try {
                const response = await deleteUser(user.id)
                if (response.code === 200) {
                    toast.success('用户删除成功')
                    fetchUsers()
                } else {
                    toast.error(response.message || '删除失败')
                }
            } catch (error) {
                console.error('删除用户失败:', error)
                toast.error(error.message || '删除用户失败')
            }
        }

        // 切换用户状态（调用真实API）
        const toggleStatus = async (user) => {
            const newStatus = user.status === 1 ? 0 : 1
            try {
                const response = await toggleUserStatus(user.id, newStatus)
                if (response.code === 200) {
                    toast.success('用户状态更新成功')
                    fetchUsers()
                } else {
                    toast.error(response.message || '状态更新失败')
                }
            } catch (error) {
                console.error('切换状态失败:', error)
                toast.error(error.message || '切换状态失败')
            }
        }

        // 关闭对话框
        const closeDialog = () => {
            showDialog.value = false
            resetForm()
        }

        // 重置表单
        const resetForm = () => {
            formData.id = null
            formData.username = ''
            formData.email = ''
            formData.password = ''
            formData.role = 'user'
            formData.status = 1
        }

        // 获取角色标签
        const getRoleLabel = (role) => {
            const roleMap = {
                admin: '管理员',
                editor: '编辑',
                user: '普通用户'
            }
            return roleMap[role] || role
        }

        // 格式化日期
        const formatDate = (dateString) => {
            if (!dateString) return '-'
            const date = new Date(dateString)
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            const hours = String(date.getHours()).padStart(2, '0')
            const minutes = String(date.getMinutes()).padStart(2, '0')
            return `${year}-${month}-${day} ${hours}:${minutes}`
        }

        onMounted(() => {
            fetchUsers()
        })

        return {
            users,
            total,
            currentPage,
            pageSize,
            searchKeyword,
            filterRole,
            showDialog,
            isEditing,
            loading,
            saving,
            formData,
            fetchUsers,
            handleSearch,
            handlePageChange,
            showAddUserDialog,
            editUser,
            saveUser,
            handleDeleteUser,
            toggleStatus,
            closeDialog,
            getRoleLabel,
            formatDate
        }
    }
}
</script>

<style scoped>
.icon {
    font-style: normal;
}

.empty-icon {
    font-size: 64px;
}

.user-management {
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.page-header h1 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    display: flex;
    align-items: center;
    gap: 12px;
}

.page-header h1 i {
    color: #4CAF50;
}

.filter-bar {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
}

.search-box {
    flex: 1;
    position: relative;
    max-width: 400px;
}

.search-box i {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
}

.search-box input {
    width: 100%;
    padding: 10px 12px 10px 40px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
}

.search-box input:focus {
    outline: none;
    border-color: #4CAF50;
}

.role-filter {
    padding: 10px 16px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
}

.user-list {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

.loading {
    padding: 60px;
    text-align: center;
    color: #666;
    font-size: 16px;
}

.loading i {
    margin-right: 8px;
}

table {
    width: 100%;
    border-collapse: collapse;
}

thead {
    background: #f8f9fa;
}

th {
    padding: 16px;
    text-align: left;
    font-weight: 600;
    color: #333;
    border-bottom: 2px solid #e9ecef;
}

td {
    padding: 16px;
    border-bottom: 1px solid #e9ecef;
    color: #666;
}

tbody tr:hover {
    background: #f8f9fa;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    flex-shrink: 0;
}

.role-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.role-badge.role-admin {
    background: #ff9800;
    color: white;
}

.role-badge.role-editor {
    background: #2196F3;
    color: white;
}

.role-badge.role-user {
    background: #9E9E9E;
    color: white;
}

.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.active {
    background: #e8f5e9;
    color: #4CAF50;
}

.status-badge.inactive {
    background: #ffebee;
    color: #f44336;
}

.actions {
    display: flex;
    gap: 8px;
}

.btn-icon {
    padding: 8px;
    background: transparent;
    border: none;
    cursor: pointer;
    color: #666;
    border-radius: 4px;
    transition: all 0.2s;
}

.btn-icon:hover {
    background: #f0f0f0;
    color: #333;
}

.btn-icon.btn-danger:hover {
    background: #ffebee;
    color: #f44336;
}

.empty-state {
    padding: 60px;
    text-align: center;
    color: #999;
}

.empty-state i {
    font-size: 64px;
    margin-bottom: 16px;
    display: block;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s;
}

.btn-primary {
    background: #4CAF50;
    color: white;
}

.btn-primary:hover {
    background: #45a049;
}

.btn-primary:disabled {
    background: #cccccc;
    cursor: not-allowed;
}

.btn-default {
    background: #f5f5f5;
    color: #666;
}

.btn-default:hover {
    background: #e0e0e0;
}

/* 对话框样式 */
.dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.dialog {
    background: white;
    border-radius: 8px;
    width: 500px;
    max-width: 90%;
    max-height: 90vh;
    overflow: auto;
}

.dialog-header {
    padding: 20px;
    border-bottom: 1px solid #e9ecef;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.dialog-header h2 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.close-btn {
    background: transparent;
    border: none;
    font-size: 20px;
    cursor: pointer;
    color: #999;
    padding: 4px;
}

.close-btn:hover {
    color: #333;
}

.dialog-body {
    padding: 20px;
}

.form-group {
    margin-bottom: 16px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #333;
}

.form-group input,
.form-group select {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
}

.form-group input:focus,
.form-group select:focus {
    outline: none;
    border-color: #4CAF50;
}

.dialog-footer {
    padding: 20px;
    border-top: 1px solid #e9ecef;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

/* 移动端响应式样式 */
@media (max-width: 768px) {
    .user-management {
        padding: 80px 16px 16px;
    }

    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
    }

    .page-header h1 {
        font-size: 20px;
    }

    .filter-bar {
        flex-direction: column;
    }

    .search-box {
        max-width: 100%;
    }

    /* 表格横向滚动 */
    .user-list {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    table {
        min-width: 800px;
    }

    th, td {
        padding: 12px 8px;
        font-size: 13px;
    }

    .user-info {
        gap: 8px;
    }

    .avatar {
        width: 32px;
        height: 32px;
        font-size: 16px;
    }

    .actions {
        gap: 4px;
    }

    .btn-icon {
        padding: 6px;
    }

    /* 对话框适配 */
    .dialog {
        width: 100%;
        max-width: 100%;
        margin: 0;
        border-radius: 0;
        max-height: 100vh;
    }

    .dialog-header,
    .dialog-body,
    .dialog-footer {
        padding: 16px;
    }
}

@media (max-width: 480px) {
    .user-management {
        padding: 80px 12px 12px;
    }

    .page-header h1 {
        font-size: 18px;
        gap: 8px;
    }

    .btn {
        padding: 8px 16px;
        font-size: 13px;
    }

    th, td {
        padding: 10px 6px;
        font-size: 12px;
    }

    .role-badge,
    .status-badge {
        padding: 3px 8px;
        font-size: 11px;
    }
}
</style>
